<?php
namespace app\controllers;
use app\utils\pay\WxPayConfig;
use app\models\Address;
use app\models\Banner;
use app\models\Category;
use app\models\Orderform;
use app\models\Cart;
use app\models\Collection;
use app\models\Orderform_commodity;
use app\models\VerifyForm;
use app\utils\pay\CLogFileHandler;
use app\utils\pay\Log;
use app\utils\pay\WxPayUnifiedOrder;
use yii\base\ErrorException;
use yii\caching\ArrayCache;
use yii\captcha\CaptchaAction;
use yii\web\Controller;
use app\models\Commodity;
use app\models\Globals;
use app\models\Attr;
use app\models\Attr_opt;
use app\models\AddressForm;
use app\models\Addressbook;
use app\common\CommonHelper;
use yii\filters\AccessControl;
use app\models\LoginForm;
use app\models\User;
use app\models\SignupForm;
use app\models\ShareForm;
use app\models\Proxy;
use app\models\ValidateCode;
use app\models\Postage_template;
use app\models\Postage_template_detail;
require_once('../utils/pay/WxPayDataBase.php');
require_once('../utils/pay/log.php');
require_once('../utils/CCPRestSDK.php');
use app\utils\pay\JsApiPay;
use app\utils\pay\WxPayApi;
use app\utils\pay\WxPayNotify;
use yii\helpers\Url;
use yii\log\Logger;

/**
 * Created by PhpStorm.
 * User: l
 * Date: 2016/7/11
 * Time: 11:44
 */
class commodityAttributeObject
{
    var $attr_name;
    var $attr_opts;
}

class WebController extends Controller
{
    public $enableCsrfValidation = false;
    public $layout = 'layout';
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['shop-bag', 'to-pay', 'new-address', 'my-address', 'addaddress', 'my-order', 'join-cart','personal-center','out'],
                'rules' => [
//                    [
//                        'actions' => ['captcha'],
//                        'allow' => true,
//                        'roles' => ['?'],
//                    ],
                    [
                        'allow' => true,
                        'actions' => ['shop-bag', 'to-pay', 'new-address', 'my-address', 'addaddress', 'my-order', 'join-cart','personal-center','out'],
                        'roles' => ['@'],
                    ],
                ]
            ],
            'corsFilter' => [
                'class' => \yii\filters\Cors::className(),
                'cors' => [
                    'Origin' => ['*'],
                    'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
                    'Access-Control-Request-Headers' => ['*'],
                    'Access-Control-Allow-Credentials' => null,
                    'Access-Control-Max-Age' => 86400,
                    'Access-Control-Expose-Headers' => []
                ],

            ],
        ];
    }

    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
//            'captcha' => [
//                'class' => 'yii\captcha\CaptchaAction',
//                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
//                'backColor'=>0x000000,//背景颜色
//                'maxLength' => 6, //最大显示个数
//                'minLength' => 4,//最少显示个数
//                'padding' => 5,//间距
//                'height'=>40,//高度
//                'width' => 130,  //宽度
//                'foreColor'=>0xffffff,     //字体颜色
//                'offset'=>4,        //设置字符偏移量 有效果
//                //'controller'=>'login',        //拥有这个动作的controller
//            ],
        ];
    }

    public function actionShare()
    {
        $leader_id = \Yii::$app->request->get('user_id');
        $data = \Yii::$app->request->post();
        $model = new ShareForm();
        if ($model->load($data) && $model->validate()) {
            $user = $model->getUser();
            if (Proxy::getProxyById($user->user_id)) {
                return $this->render('result', ['title' => '申请失败', 'message' => '您已拥有代理!']);
            } else {
                $result = \Yii::$app->db->createCommand()->insert('hcps_proxy_apply', [
                    'user_id' => $user->user_id,
                    'content' => $model->content,
                    'mobile' =>$model->mobile,
                    'leader_id' => $leader_id,
                    'create_time' => CommonHelper::getCurrentTime()
                ])->execute();
                if ($result) {
                    return $this->render('result', ['title' => '申请成功', 'message' => '请等待审核!']);
                } else {
                    return $this->render('result', ['title' => '申请失败', 'message' => '请重试!']);
                }
            }

        }
        return $this->render('share', ['model' => $model]);

    }

    public function actionShopBag()
    {
        $cart = new Cart();
        $global=new Globals();
        $shopName=$global->getShopName();
        $carts = $cart->getCarts();
        //所有购物车中的商品ID
        $carts_ids = $cart->getCartCommodityIds();
        $commodities = array();//未过期的商品
        $commodities_out_date = array();
        $cartsReal = array();
        $attrsAll = array();
        $commodity = new Commodity();
        for ($i = 0; $i < count($carts); $i++) {
//            $item = $commodity->getCommodityById($carts[$i]['commodity_id']);
//
//            if ($item) {
//                array_push($cartsReal, $carts[$i]);
//                array_push($commodities, $item);
//                $attrsAll[count($commodities) - 1] = array();
//
//                $attrString = $carts[$i]['opt_ids_json'];
//                $attrsOne = json_decode($attrString, true);
//                for ($j = 0; $j < count($attrsOne); $j++) {
//                    $attr = new Attr_opt();
//                    $item = $attr->getAttrById($attrsOne[$j]);
//
//                    array_push($attrsAll[count($commodities) - 1], $item);
//                }
//            }
//        }
            //通过商品ID找到商品表里的stock_num和is_sale
            $stock_num = Commodity::find()->where(['commodity_id' => $carts_ids[$i]])->select('stock_num')->scalar();
            $is_sale = Commodity::find()->where(['commodity_id' => $carts_ids[$i]])->select('is_sale')->scalar();

            if ($is_sale == 1) {//如果有上架
                //获取每个收藏的商品信息
                $item = $commodity->getCommodityById($carts[$i]['commodity_id']);

                if ($item) {
                    array_push($cartsReal, $carts[$i]);
                    array_push($commodities, $item);
                    $attrsAll[count($commodities) - 1] = array();

                    $attrString = $carts[$i]['opt_ids_json'];//购物车商品规格数值
                    $attrsOne = json_decode($attrString, true);//购物车规格数值对象
                    for ($j = 0; $j < count($attrsOne); $j++) {
                        $attr = new Attr_opt();
                        $item = $attr->getAttrById($attrsOne[$j]);//获取商品属性表里的每个对象,然后加入到attrsAll二维数字的最后一项

                        array_push($attrsAll[count($commodities) - 1], $item);
                    }
                }
            } else {
                $item = $commodity->getCommodityById($carts[$i]['commodity_id']);

                if ($item) {
                    array_push($cartsReal, $carts[$i]);
                    array_push($commodities_out_date, $item);
                    $attrsAll[count($commodities) - 1] = array();

                    $attrString = $carts[$i]['opt_ids_json'];
                    $attrsOne = json_decode($attrString, true);
                    for ($j = 0; $j < count($attrsOne); $j++) {
                        $attr = new Attr_opt();
                        $item = $attr->getAttrById($attrsOne[$j]);

                        array_push($attrsAll[count($commodities) - 1], $item);
                    }
                }
            }
        }
        //commodities购物车里的商品对应商品表的全部数据,cartsReal为用户购物车里对应购物车表的每个商品
        return $this->render('shop-bag', ['commodities' => $commodities, 'attrsAll' => $attrsAll, 'carts' => $cartsReal,'commodities_out_date'=>$commodities_out_date,'shopName'=>$shopName]);
    }

    public function actionDeleteCart()
    {
        $request = \Yii::$app->request;
        $cart_id = $request->get('cart_id');

        $result = \Yii::$app->db->createCommand()->update('hcps_cart', [
            'del_flag' => 0], ['cart_id' => $cart_id])->execute();
    }

    public function actionDeleteCollection()
    {
        $request = \Yii::$app->request;
        $collection_id = $request->get('collection_id');

        $result = \Yii::$app->db->createCommand()->update('hcps_collection', [
            'del_flag' => 0], ['collection_id' => $collection_id])->execute();
    }





    public function actionToPay()
    {
        $request = \Yii::$app->request;
        $user_id=\Yii::$app->user->id;
        $global=new Globals();
        $shopName=$global->getShopName();
        $sums = $request->get('sums');
        $attrString = $request->get('attr_opt_ids');
        $commodity_idString = $request->get('commodity_ids');
        $cart_idString = $request->get('cart_ids');
        if (!$cart_idString) {
            $cart_idString = -1;
        }
        $share_id = $request->get('share_id');
        $openid=isset($_COOKIE['openid'])?$_COOKIE['openid']:'';
        if(empty($openid)){
            $jsapi=new JsApiPay();
            if (!isset($_GET['code'])){
                //触发微信返回code码
                //设置我们自己的回调url
                $redirect_url=Url::to(['web/to-pay','attr_opt_ids'=>$attrString,'share_id'=>$share_id,'commodity_ids'=>$commodity_idString,'cart_ids'=>$cart_idString],true);
                $baseUrl = urlencode($redirect_url);
                $toUrl=$jsapi->getCode($baseUrl);
                return $this->redirect($toUrl,301);
            } else {
                //获取code码，以获取openid
                $code = $_GET['code'];
                $info = $jsapi->GetOpenid($code);
                if($info){
                    setcookie('access_token',$info['access_token'],time()+86400);
                    setcookie('openid',$info['openid'],time()+86400);
                }
            }
        }
        $attrsOne = json_decode($attrString, true);
        $commoditiesOne = json_decode($commodity_idString, true);
        $sums = json_decode($sums,true);
        $attrsAll = array();
        $commoditiesAll = array();

        for ($i = 0; $i < count($commoditiesOne); $i++) {

            $commodity = new Commodity();
            $item = $commodity->getCommodityById($commoditiesOne[$i]);
            array_push($commoditiesAll, $item);

            $attrsAll[$i] = array();

            for ($j = 0; $j < count($attrsOne[$i]); $j++) {
                $attr = new Attr_opt();
                $item = $attr->getAttrById($attrsOne[$i][$j]);
                array_push($attrsAll[$i], $item);
            }
        }

        //获取默认地址
        $address = new Addressbook();
        $default = $address->getDefaultAddress();
        $addresslist = $address->getAddress();

        //获取运费模板
        $postageTemplates = array();
        foreach ($commoditiesAll as $commodity) {
            $postage_template_id = $commodity['postage_template_id'];
            $template = Postage_template::find()->select(['id','name', 'default_unit_price'])
                ->where(['id'=>$postage_template_id, 'del_flag'=>1])
                ->one();
            if ($template != null) {
                $details = (new Postage_template())->getDetails($postage_template_id);
                $provinceUnitPrice = [];
                if (count($details) > 0) {
                    foreach ($details as $detail) {
                        foreach (explode(', ', $detail['province_name']) as $province_name) {
                            $provinceUnitPrice[$province_name] = $detail['unit_price'];
                        }
                    }
                }
                $postageTemplates[$commodity['commodity_id']] =
                    ["default"=>$template['default_unit_price'], "details"=>$provinceUnitPrice];
            }
        }

        $noRemind= \Yii::$app->db->createCommand('SELECT no_remind FROM hcps_user WHERE  user_id=:id ')->bindValue(':id',$user_id)->queryScalar();
        return $this->render('to-pay', ['commodities' => $commoditiesAll, 'attrsAll' => $attrsAll, 'address' => $default,
            'cart_idString' => $cart_idString, 'attrString' => $attrString, 'share_id' => $share_id,'no_remind'=>$noRemind,'shopName'=>$shopName,
            'addresslist'=>$addresslist,'postage_templates' => json_encode($postageTemplates),'sums' => $sums]);
    }

    public function actionNewAddress()
    {
        return $this->render('new-address');
    }

    public function actionCreateAddress(){
        $data=\Yii::$app->request->post();
        $user_id = \Yii::$app->user->id;
        $address = new Addressbook();
        $addressDefault = $address ->getDefaultAddress();

        if($addressDefault){
            $isDefault = "0";
        }else{
            $isDefault = "1";
        }

        $result =\Yii::$app->db->createCommand()->insert('hcps_addressbook', [
            'user_id' => $user_id,
            'fullname' => $data['fullname'],
            'mobile' => $data['etPhone'],
            'province'=>$data['cho_Province'],
            'city'=>$data['cho_City'],
            'district'=>$data['cho_Area'],
            'address'=>$data['cho_detail'],
            'is_default'=>$isDefault,
            'create_time'=>CommonHelper::getCurrentTime()
        ])->execute();

        if($result['status']==1){
            return json_encode(['code'=>1]);
        }else{
            return json_encode(['code'=>0]);
        }
    }

    public function actionDeleteAddress()
    {
        $request = \Yii::$app->request;
        $addressbook_id = $request->get('addressbook_id');

        $result = \Yii::$app->db->createCommand()->update('hcps_addressbook', [
            'del_flag' => 0], ['addressbook_id' => $addressbook_id])->execute();

        if($result['status']==1){
            return json_encode(['code'=>1]);
        }else{
            return json_encode(['code'=>0]);
        }
    }

    public function actionDefault()
    {

        $request = \Yii::$app->request;
        $addressbook_id = $request->get('addressbook_id');

        $address = new Addressbook();
        $addressDefault = $address->getDefaultAddress();

        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            $db->createCommand()->update('hcps_addressbook', [
                'is_default' => 0], ['addressbook_id' => $addressDefault['addressbook_id']])->execute();

            $db->createCommand()->update('hcps_addressbook', [
                'is_default' => 1], ['addressbook_id' => $addressbook_id])->execute();

            $transaction->commit();

            return json_encode(['code'=>1]);
        } catch (\Exception $e) {

            $transaction->rollBack();

            throw $e;
        }
    }
   //我的订单
    public function actionMyOrder()
    {
        $request = \Yii::$app->request;
        $status = $request->get('status');
        $global=new Globals();
        $shopName=$global->getShopName();
        $order = new Orderform();
        if ($status == 9) {
            $orders = $order->getOrders();
        } else if($status==2){

            $order2 = $order->getOrdersByStatus(2);
            $order3 = $order->getOrdersByStatus(3);
            $order5 = $order->getOrdersByStatus(5);
            $order6 = $order->getOrdersByStatus(6);
            $orders = array_merge($order2 , $order3 , $order5,$order6);
        } else{
            $orders = $order->getOrdersByStatus($status);
        }

        $commodityInOrders = array();
        $commodityAttrsInOrders = array();

        $orderCommodities = array();
        for ($i = 0; $i < count($orders); $i++) {

            $orderCommodities[$i] = array();
            $commodityInOrders[$i] = array();
            $commodityAttrsInOrders[$i] = array();
            $orderCommodity = new Orderform_commodity();
            $orderCommodities[$i] = $orderCommodity->getOrderCommodities($orders[$i]['orderform_id']);

            for ($j = 0; $j < count($orderCommodities[$i]); $j++) {
                $commodity = new Commodity();
                $itemCommodity = $commodity->getCommodityById($orderCommodities[$i][$j]['commodity_id']);
                array_push($commodityInOrders[$i], $itemCommodity);

                $attrString = $orderCommodities[$i][$j]['opt_ids_json'];
                $attrsOne = json_decode($attrString, true);
                for ($n = 0; $n < count($attrsOne); $n++) {
                    $attr = new Attr_opt();
                    $attrItem = $attr->getAttrById($attrsOne[$n]);

                    array_push($commodityAttrsInOrders[$i], $attrItem);
                }
            }
        }

        return $this->render('my-order', ['commodityInOrders' => $commodityInOrders, 'orders' => $orders,
            'commodityAttrsInOrders' => $commodityAttrsInOrders, 'orderCommodities' => $orderCommodities, 'status' => $status,'shopName'=>$shopName]);
    }

    //我的收藏
    public function actionMyCollection(){
        $global=new Globals();
        $shopName=$global->getShopName();
        $collection = new Collection();
        //获得收藏的所有商品信息
        $collections = $collection->getCollections();
        //获得收藏的所有商品的ID
        $collection_ids = $collection->getCollectionCommodityIds();

        $commodities = array();//这些商品是未过期的
        $commodities_out_date =array();//这些收藏的商品已过期
        $collectionsReal = array();
        $commodity = new Commodity();
        for($i = 0;$i<count($collection_ids);$i++){
            //通过商品ID找到商品表里的stock_num和is_sale
            $stock_num = Commodity::find()->where(['commodity_id'=>$collection_ids[$i]])->select('stock_num')->scalar();
            $is_sale = Commodity::find()->where(['commodity_id'=>$collection_ids[$i]])->select('is_sale')->scalar();

            if($is_sale==1){//如果有上架
                //获取每个收藏的商品信息
                $item = $commodity->getCommodityById($collections[$i]['commodity_id']);

                if ($item) {
                    array_push($collectionsReal, $collections[$i]);
                    array_push($commodities, $item);
                }
            }else{
                $item = $commodity->getCommodityById($collections[$i]['commodity_id']);

                if ($item) {
                    array_push($collectionsReal, $collections[$i]);
                    array_push($commodities_out_date, $item);
                }
            }
        }
        return $this->render('my-collection', ['commodities' => $commodities, 'collections' => $collectionsReal,'commodities_out_date' => $commodities_out_date,'shopName'=>$shopName]);
    }
    //加入我的个人中心
    public function actionPersonalCenter(){
        $user_id=\Yii::$app->user->id;

        $openid=isset($_COOKIE['openid'])?$_COOKIE['openid']:'';
        $access_token=isset($_COOKIE['access_token'])?$_COOKIE['access_token']:'';
        $jsapi=new JsApiPay();
        if(empty($openid)||empty($access_token)||$jsapi->isAccess_tokenOutDate($openid,$access_token)){
            if (!isset($_GET['code'])){
                //触发微信返回code码
                //设置我们自己的回调url
                $redirect_url=Url::to(['web/personal-center'],true);
                $baseUrl = urlencode($redirect_url);
                $toUrl=$jsapi->getCode($baseUrl);
                return $this->redirect($toUrl,301);
            } else {
                //获取code码，以获取openid
                $code = $_GET['code'];
                $info = $jsapi->GetOpenid($code);
                if($info){
                    setcookie('openid',$info['openid'],time()+86400);
                    $openid=$info['openid'];
                    $infoOpenid=$info['openid'];
                    $infoAccess_token=$info['access_token'];
                    $infoRefresh_token=$info['refresh_token'];
                    if(!$jsapi->isAccess_tokenOutDate($infoOpenid,$infoAccess_token)){
                        setcookie('access_token',$info['access_token'],time()+86400);
                        $access_token=$info['access_token'];
                    }
                    else{
                        if($jsapi->refreshAccess_token($infoRefresh_token)){
                            $appid=WxPayConfig::APPID;
                            $refreshStr="https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=".$appid."&grant_type=refresh_token&refresh_token=".$infoRefresh_token;
                            $result=json_decode(file_get_contents($refreshStr));
                            setcookie('access_token',$result->access_token,time()+86400);
                            $access_token=$result->access_token;
                        }
                        //TODO yichangchuli
                    }
                }
                //TODO yichangchuli
            }
        }
        if (!empty($openid)&&!empty($access_token)){
            $str = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid . "&lang=zh_CN";
            $result = json_decode(file_get_contents($str));
            $headimgurl = $result->headimgurl;


            $hasheadimgurl = (new \yii\db\Query())->select(['headimgurl'])->from('hcps_user')->where(['user_id' => $user_id])->scalar();
            if (!$hasheadimgurl) {
               \Yii::$app->db->createCommand()->update('hcps_user', [
                    'headimgurl' => $headimgurl], ['user_id'=>$user_id])->execute();
            }

            $headerimgurl = (new \yii\db\Query())->select(['headimgurl'])->from('hcps_user')->where(['user_id' => $user_id])->scalar();
        }
        else{
            $defaulturl='https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3354715732,987813345&fm=21&gp=0.jpg';
            $headerimgurl = $defaulturl;
        }

          return $this->render('personal-center',['headimgurl'=>$headerimgurl]);
    }

    public function actionPay()
    {
        $jsapi=new JsApiPay();
        $openid=$_COOKIE['openid'];
        $request = \Yii::$app->request;
        $order_id = $request->post('order_id');
        $total  = $request->post('total');
        $input = new WxPayUnifiedOrder();
        $input->SetBody('商品订单-' . $order_id);
        $input->SetOut_trade_no($order_id);
        //测试api floatval($total)*100
        $input->SetTotal_fee(1);
        $input->SetNotify_url(Url::to(['web/wxpayresult'], true));
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openid);
        $payorder = WxPayApi::unifiedOrder($input);
        $jsApiParameters = $jsapi->GetJsApiParameters($payorder);

        $jsApi=json_decode($jsApiParameters);
        return json_encode(['js'=>$jsApi,'orderform_id'=>$order_id]);

    }

    public function actionSlide()
    {
        $banners = $post = \Yii::$app->db->createCommand('SELECT * FROM hcps_banner WHERE del_flag=:id')
            ->bindValue(':id', 1)
            ->queryAll();
        return $this->render('slide', ['banners' => $banners]);
    }

    public function actionHome()
    {
        $data = \Yii::$app->request->post();
        $user_id=\Yii::$app->user->id;
        $global=new Globals();
        $shopName=$global->getShopName();
        $category = new Category();
        $categoryList = $category->getFirstCategoryList();
        if(!$user_id){
            if (\Yii::$app->user) {
                $share_id=-1;
            }
            else {
                $share_id=\Yii::$app->user->id;
            }
        }else{
            $share_id=$user_id;
        }
        if ($data) {
            $commodity_name = $data['input_text'];
            $is_hot = 2;
            $commdityModel = new Commodity();
            $searchResult = $commdityModel->getCommodityList(0, 3, $commodity_name);
            $title = "搜索结果";
            return $this->render('list', ['commodities' => $searchResult, 'title' => $title, 'is_hot' => $is_hot,'share_id'=>$share_id]);
        } else {
            $commdityModel = new Commodity();
            $banners = \Yii::$app->db->createCommand('SELECT * FROM hcps_banner WHERE del_flag=:id')
                ->bindValue(':id', 1)
                ->queryAll();
            //   var_dump($banners);
//            $banners = array();
//            foreach ($bannersResult as $key => $value) {
//                $banners[] = '<img class="banner" src=' . $value['pic_url'] . '/>';
//            }
            $commoditylist = $commdityModel->getCommodityList(2, 0, 0);
            return $this->render('home', ['commoditylist' => $commoditylist, 'banners' => $banners,'share_id'=>$share_id,'categoryList' => $categoryList,'shopName'=>$shopName]);
        }
    }


    public function actionDetailContent(){
        $request = \Yii::$app->request;
        $commodity_id = $request->get('commodity_id');
        $commdityModel = new Commodity();
        $commodityDetail = $commdityModel->getCommodity($commodity_id); //商品信息
        return $this->render('detail-content',['commodityDetail' => $commodityDetail]);
    }

    public function actionCleanOpenid(){
        setcookie('openid',"");
        setcookie('access_token',"");
    }

    public function actionBannerDetail(){
        $request = \Yii::$app->request;
        $banner_id = $request->get('banner_id');
        $banner = new Banner();
        $bannerContent = $banner->getBannerContent($banner_id);
        return $this->render('banner-detail',['bannerContent' => $bannerContent]);
    }

    public function actionJoinCollection(){
        //处理ajax请求,接收detail页面的一些信息,插入收藏表
        $request = \Yii::$app->request;
        $commodity_id = $request->get('commodity_id');
        $user_id = \Yii::$app->user->id;
        $create_time = CommonHelper::getCurrentTime();
        $collectionModel = new Collection();
        $collectionData = $collectionModel->getOneCollection($user_id, $commodity_id); //查询相同商品是否已添加
        $collection_id = $collectionData['collection_id'];
        if (!$collectionData) {
            $result = \Yii::$app->db->createCommand()->insert('hcps_collection', [ //未添加则插入数据库
                'user_id' => $user_id,
                'commodity_id' => $commodity_id,
                'create_time' => $create_time,
            ])->execute();
        } else {
            $result = \Yii::$app->db//已添加则更新时间.
            ->createCommand()->update('hcps_collection', ['create_time' => $create_time], 'collection_id="' . $collection_id . '"')
                ->execute();
        }
        var_dump(json_encode($collectionData, true));
    }

    public function actionJoinCart()
    {       //处理ajax请求
        $request = \Yii::$app->request;
        $commodity_id = $request->get('commodity_id');
        $attr_opt_ids = $request->get('attr_opt_ids');
        $shop_num = $request->get('shop_num');
        $user_id = \Yii::$app->user->id;
        $create_time = CommonHelper::getCurrentTime();
        $cartModel = new Cart();
        $cartData = $cartModel->getOneCart($user_id, $commodity_id, $attr_opt_ids); //查询相同规格商品是否已添加
        $cart_id = $cartData['cart_id'];
        if (!$cartData) {
            $result = \Yii::$app->db->createCommand()->insert('hcps_cart', [ //未添加则插入数据库
                'user_id' => $user_id,
                'commodity_id' => $commodity_id,
                'opt_ids_json' => $attr_opt_ids,
                'create_time' => $create_time,
                'shop_num' => $shop_num
            ])->execute();
        } else {
            $result = \Yii::$app->db//已添加则更新时间.
            ->createCommand()->update('hcps_cart', ['create_time' => $create_time], 'cart_id="' . $cart_id . '"')
                ->execute();
        }
        var_dump(json_encode($cartData, true));
    }
    public function actionCheckSignature()
    {
        \Yii::getLogger()->log("开始写自定义日志",Logger::LEVEL_ERROR);
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $echostr=$_GET['echostr'];
        $token = 'zhongpei2015';
        \Yii::info('signature=>'.$signature.'timestamp=>'.$timestamp.'nonce=>'.$nonce.'token=>'.$token,'controller');

        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        \Yii::info('tmpStr=>'.$tmpStr,'controller');
        if( $tmpStr == $signature ){
            ob_clean();
            echo $echostr;
            exit();
        }else{
            echo 'false';
            exit();
        }
    }

    public function actionCreateOrder()
    {
        $jsapi=new JsApiPay();
        $openid=$_COOKIE['openid'];
        $userId = \Yii::$app->user->id;
        $user = new User();
        $item = $user->findIdentity($userId);
        $username = $item['username'];
        $db = \Yii::$app->db;
        $orderId = CommonHelper::generateOrderId($userId);
        $request = \Yii::$app->request;
        $share_id = $request->post('share_id');
        if($share_id==$userId){
            $share_id=-1;
        }
        $commodity_ids = $request->post('commodity_ids');
        $commodity_sums = $request->post('commodity_sums');

        $address_id = $request->post('address_Id');
        $postage = $request->post('postage');
        $total = $request->post('totalMoney');
        $remarks = $request->post('remarks');
        $cart_ids = $request->post('cart_ids');
        $attr_ids = $request->post('attr_ids');
        $cart_id = json_decode($cart_ids, true);
        $attr_id = json_decode($attr_ids, true);
        $commodity_id = json_decode($commodity_ids, true);
        $commodity_sum = json_decode($commodity_sums, true);

        $transaction = $db->beginTransaction();

        try {
            $db->createCommand()->insert('hcps_orderform', [
                'orderform_id' => $orderId,
                'user_id' => $userId,
                'create_time' => CommonHelper::getCurrentTime(),
                'money' => floatval($total) - floatval($postage),
                'postage' => $postage,
                'addressbook_id' => $address_id,
                'user_name' => $username,
                'proxy_id'=>$share_id,
                'remarks'=>$remarks,
            ])->execute();

            for ($j = 0; $j < count($commodity_id); $j++) {
                $db->createCommand()->insert('hcps_orderform_commodity', [
                    'orderform_id' => $orderId,
                    'commodity_id' => $commodity_id[$j],
                    'commodity_num' => $commodity_sum[$j],
                    'opt_ids_json' => json_encode($attr_id[$j]),
                    'create_time' => CommonHelper::getCurrentTime()
                ])->execute();
            }

            for ($j = 0; $j < count($cart_id); $j++) {
                $db->createCommand()->update('hcps_cart', [
                    'del_flag' => 0], ['cart_id' => $cart_id[$j]])->execute();
            }

            for($j = 0;$j <count($commodity_id);$j++){
                //先拿到商品表里的stock_num;
                $stock_num = Commodity::find()->select('stock_num')->where(['commodity_id'=>$commodity_id[$j]])->scalar();
                // 减少库存前,再判断一次库存是否小于订单量
                    $db->createCommand()->update('hcps_commodity',[
                        'stock_num' => $stock_num-$commodity_sum[$j]],
                        ['commodity_id'=>$commodity_id[$j]]
                    )->execute();
                $result =  (new \yii\db\Query())
                    ->select('stock_num')
                    ->from('hcps_commodity')
                    ->where(['commodity_id' => $commodity_id[$j]])
                    ->one();
                if($result['stock_num'] < 0){
                    throw new Exception('库存不足');
                }
            }

            $transaction->commit();

        } catch (\Exception $e) {

            $transaction->rollBack();

            throw $e;
        }
        $input = new WxPayUnifiedOrder();
        $input->SetBody('商品订单-' . $orderId);
        $input->SetOut_trade_no($orderId);
        //测试api floatval($total)*100
        $input->SetTotal_fee(1);
        $input->SetNotify_url(Url::to(['web/wxpayresult'], true));
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openid);
        $payorder = WxPayApi::unifiedOrder($input);
        $jsApiParameters = $jsapi->GetJsApiParameters($payorder);
        $jsApi=json_decode($jsApiParameters);
        return json_encode(['js'=>$jsApi,'orderform_id'=>$orderId]);
    }
    public function actionGetorderstatus(){
        $request = \Yii::$app->request;
        $orderform_id = $request->post('orderform_id');

        $result=\Yii::$app->db->createCommand('SELECT * FROM hcps_orderform WHERE orderform_id=:id')
            ->bindParam(':id', $orderform_id)->queryOne();
        if($result['status']==1){
            return json_encode(['code'=>1]);
        }else{
            return json_encode(['code'=>0]);
        }

    }
    public function actionWxpayresult(){
        $logHandler= new CLogFileHandler("../utils/logs/".date('Y-m-d').'.log');
        $log = Log::Init($logHandler, 15);
        Log::DEBUG("begin notify");
        Log::DEBUG("-----start---");
        $notify = new WxPayNotify();
        try{
            $data=$notify->notify($log);
            Log::DEBUG("notify result".json_encode($data));
//            $data=json_decode($result);
//            \app\utils\pay\Log::DEBUG("orderform_id--->".$data->va);
        }catch(\Exception $e){
            Log::DEBUG("exception-->".$e);
        }
        if($data['result_code']=='SUCCESS'){
            try{
                //更新订单状态
                $saveresult=\Yii::$app->db->createCommand('UPDATE hcps_orderform SET status=1 WHERE orderform_id=:id and status=0')->bindParam(':id',$data['out_trade_no'])->execute();

                $orderCommodity = new Orderform_commodity();
//                $orderCommodities = $orderCommodity->getOrderCommodities($data['out_trade_no']);

//                $commodity = new Commodity();
//
//                for($j = 0; $j < count($orderCommodities); $j++){
//                    //支付成功后,销量不加
//                    //$commodity_sale_num = $commodity ->getCommodityNum($orderCommodities[$j]['commodity_id']);
//                    //$commodity_sales_num = $commodity_sale_num + $orderCommodities[$j]['commodity_num'];
//                    \Yii::$app->db->createCommand()->
//                    update('hcps_commodity', ['commodity_id=' . $orderCommodities[$j]['commodity_id'])
//                        ->execute();
//                }

            }catch(\Exception $e){
                Log::DEBUG("exception-->".$e);
            }
            Log::DEBUG("save result-->".$saveresult);
            return '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        }else{
            return "fail";
        }

      //  \app\utils\pay\Log::DEBUG("notify message".$notify->GetReturn_msg());
    }

    public function actionChangeStatus(){
        $data = \Yii::$app->request->post();
        $status = $data['status'];
        if($status == 8){

            $orderform_id = $data['orderform_id'];
            $commodity_id = $data['commodity_id'];//这是一个数组
            $commodity_num = $data['commodity_num'];//这是一个数组
            for($i = 0;$i<count($commodity_id);$i++){

                $stock_num = Commodity::find()->where(['commodity_id'=>$commodity_id[$i]])->select('stock_num')->scalar();
                \Yii::$app->db->createCommand()
                    ->update('hcps_commodity', ['stock_num'=>$commodity_num[$i]+$stock_num], 'commodity_id='.$commodity_id[$i])->execute();
            }
            $result = \Yii::$app->db->createCommand()
                ->update('hcps_orderform', ['status' => $status], 'orderform_id=' . $orderform_id)->execute();

        }else{
            $orderform_id = $data['orderform_id'];

            $result = \Yii::$app->db->createCommand()
             ->update('hcps_orderform', ['status' => $status], 'orderform_id=' . $orderform_id)->execute();
        }

        if($result['status']==1){
            return json_encode(['code'=>1]);
        }else{
            return json_encode(['code'=>0]);
        }
    }

    public function actionCommentOrder(){
        $data = \Yii::$app->request->post();
        $orderform_id = $data['orderform_id'];
        $comment_rank = $data['comment_rank'];

        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();

        $orderCommodity = new Orderform_commodity();
        $orderCommodities = $orderCommodity->getOrderCommodities($orderform_id);

        $commodity = new Commodity();

        try {
            $db->createCommand()->update('hcps_orderform', ['is_comment' => 1], 'orderform_id=' . $orderform_id)->execute();

            for ($j = 0; $j < count($orderCommodities); $j++) {
                $commodityResult = $commodity ->getCommodityById($orderCommodities[$j]['commodity_id']);
                if($comment_rank == 0){
                    $db->createCommand('UPDATE hcps_commodity SET bad_comment=bad_comment + 1 WHERE commodity_id=:id ')->bindParam(':id',$orderCommodities[$j]['commodity_id'])->execute();

//                    $commodity_bad_num = $commodityResult['bad_comment'] + 1;
//                    $db->createCommand()->update('hcps_commodity',
//                        ['bad_comment' => $commodity_bad_num], 'commodity_id=' . $orderCommodities[$j]['commodity_id'])
//                        ->execute();
                }else if($comment_rank == 1){
                    $db->createCommand('UPDATE hcps_commodity SET middle_comment=middle_comment + 1 WHERE commodity_id=:id ')->bindParam(':id',$orderCommodities[$j]['commodity_id'])->execute();

                }else{
                    $db->createCommand('UPDATE hcps_commodity SET good_comment=good_comment + 1 WHERE commodity_id=:id ')->bindParam(':id',$orderCommodities[$j]['commodity_id'])->execute();

                }

            }

            $transaction->commit();

            return json_encode(['code'=>1]);
        } catch (\Exception $e) {

            $transaction->rollBack();

            throw $e;
        }
    }

    public function actionList()
    {
        $request = \Yii::$app->request;
        $is_hot = $request->get('is_hot');

        $commdityModel = new Commodity();
        $hotCommodities = $commdityModel->getCommodityList(0, 1, 0);
        $newCommodities = $commdityModel->getCommodityList(0, 0, 0);

        if ($is_hot == 1) {
            $title = "最热商品";
            return $this->render('list', ['commodities' => $hotCommodities, 'title' => $title, 'is_hot' => $is_hot]);
        } else if ($is_hot == 0) {
            $title = "最新上架";
            return $this->render('list', ['commodities' => $newCommodities, 'title' => $title, 'is_hot' => $is_hot]);
        } else if ($is_hot == 2) {
            $title = "所有商品";
            return $this->render('list', ['commodities' => $newCommodities, 'title' => $title, 'is_hot' => $is_hot]);
        }
    }

    public function actionMyAddress()
    {
        $addressModel = new Addressbook();
        $addresslist = $addressModel->getAddress();
        return $this->render('my-address', ['addresslist' => $addresslist]);
    }

    public function actionChooseAddress()
    {
        $sums = \Yii::$app->request->get('sums');
        $commodity_ids = \Yii::$app->request->get('commodity_ids');
        $cart_ids = \Yii::$app->request->get('cart_ids');
        $attr_opt_ids = \Yii::$app->request->get('attr_opt_ids');
        $addressModel = new Addressbook();
        $addresslist = $addressModel->getAddress();
        return $this->render('choose-address',
                ['addresslist'  => $addresslist,
                 'sums'         => $sums,
                 'attr_opt_ids' => $attr_opt_ids,
                 'commodity_ids'=> $commodity_ids,
                 'cart_ids'     => $cart_ids,
                ]);
    }

    public function actionLogin()
    {
        if (!\Yii::$app->user->isGuest) {
            return $this->redirect(['index.php/web/home']);
        }
        $model = new LoginForm();

        if(\Yii::$app->request->post()){
            $data=\Yii::$app->request->post();
            $userName=$data['LoginForm']['username'];
            $type=(new \yii\db\Query())->select(['type'])->from('hcps_user')->where(['username' => $userName])->scalar();
            if($type==2){
                $this->redirect('login?type=2');
//                 var_dump(11);

            }
            else{
                if ($model->load(\Yii::$app->request->post()) && $model->login()) {
                    return $this->goBack(['index.php/web/home']);
                }
            }

        }



        return $this->render('login', [
            'model' => $model,
        ]);
    }

    public function actionOut(){
        \Yii::$app->user->logout();
        return $this->redirect(['index.php/web/home']);
        //return $this->goBack();用这个路径会不对
    }

    //结算佣金
    public function actionSettlementCommission()
    {

        $data = \Yii::$app->request->post();
        $orderform_id = $data['orderform_id'];
        $orderCommodity = new Orderform_commodity();
        $orderCommodities = $orderCommodity->getOrderCommodities($orderform_id);
        $commodity = new Commodity();
        for ($j = 0; $j < count($orderCommodities); $j++) {
            $commodity_id = $orderCommodities[$j]['commodity_id'];
            $commodity_num = $orderCommodities[$j]['commodity_num'];
            $sales_num = Commodity::find()->where(['commodity_id'=>$commodity_id])->select('sales_num')->scalar();
            \Yii::$app->db->createCommand()->update('hcps_commodity', ['sales_num'=>$commodity_num+$sales_num], 'commodity_id='.$commodity_id)->execute();
        }
//        $user_id = \Yii::$app->user->id;
        $proxy_id = $data['proxy_id'];
        $orderform_money = $data['money'];
        $db = \Yii::$app->db;
        $outerTransaction = $db->beginTransaction();
        try {
            $db->createCommand()->update('hcps_orderform', ['status' => 7,], 'orderform_id=' . $orderform_id)->execute();
            \Yii::info("begin calcultating brokerage");
            $this->calculateBrokerage($db, $proxy_id, $orderform_id, $orderform_money);
            $outerTransaction->commit();

            return json_encode(['code' => 1]);
        } catch (\Exception $e) {
            \Yii::info('catch exception, roll back');
            $outerTransaction->rollBack();
            throw $e;
        }
    }

    private function calculateBrokerage($db, $proxy_id, $orderform_id, $orderform_money)
    {
        $user_id = 13;
        //查找佣金比例
        $brokerage_rate = $db->createCommand('SELECT * FROM hcps_admin')->queryOne();
        $first_rate = $brokerage_rate['first_rate'];
        $second_rate = $brokerage_rate['second_rate'];
        $third_rate = $brokerage_rate['third_rate'];
        $brokerage_rates = [1=>$first_rate, 2=>$second_rate, 3=>$third_rate];
        //查找代理商
        $brokerage_relations = $db
            ->createCommand(
                'SELECT * FROM hcps_brokerage_relationship WHERE customer_user_id = :user_id AND del_flag = 1')
            ->bindValue(':user_id', $user_id)
            ->queryAll();
        $agents = [];
        $max_grade = 3;
        if (count($brokerage_relations) > 0 ) {
            //已有代理关系
            for ($grade = 1; $grade <= $max_grade; $grade++) {
                $brokerage_relation = $db
                    ->createCommand(
                        'SELECT * FROM hcps_brokerage_relationship
                         WHERE customer_user_id = :user_id AND agent_grade = :grade AND del_flag = 1')
                    ->bindValue(':user_id', $user_id)
                    ->bindValue('grade', $grade)
                    ->queryOne();
                if ($brokerage_relation) {
                    $agents[$grade] = $brokerage_relation['agent_user_id'];
                }
            }
        }
        else if ($proxy_id != -1) {
            //绑定代理关系
            $grade = 0;
            $proxy = ['leader_id' => $proxy_id];
            do {
                if ($grade > 0) {
                    if ($grade <= $max_grade) {
                        $agents[$grade] = $proxy_id;
                    }
                    $sql = $db->createCommand()->insert('hcps_brokerage_relationship', [
                        'customer_user_id' => $user_id,
                        'agent_user_id' => $proxy_id,
                        'agent_grade' => $grade,
                        'create_time' => CommonHelper::getCurrentTime()
                    ])->execute();
                }
                $grade++;
                $proxy_id = $proxy['leader_id'];
                $proxy = $db
                    ->createCommand(
                        'SELECT * FROM hcps_proxy WHERE user_id=:id and del_flag = 1')
                    ->bindValue(':id', $proxy_id)
                    ->queryOne();
            } while ($proxy && $proxy['leader_id'] != -1);
        }
        //计算佣金
        for ($grade = 1; $grade <= count($agents); $grade++) {
            $sql = $db->createCommand()->insert('hcps_borkerage', [
                'user_id' => $agents[$grade],
                'brokerage_money' => floatval(bcmul($orderform_money, $brokerage_rates[$grade], 2)),
                'create_time' => CommonHelper::getCurrentTime(),
                'orderform_money' => $orderform_money,
                'orderform_id' => $orderform_id,
            ])->execute();
        }
    }

    public function actionRegister()
    {

        if (!\Yii::$app->user->isGuest) {
            return $this->redirect(['index.php/web/home']);
        }



        //通过验证码验证了
        $data = \Yii::$app->request->post();
        $model = new SignupForm();
        if ($model->load($data) && $model->validate()) {

            $user = new User();
            $user->username = $data['SignupForm']['username'];
            $user->password = \Yii::$app->getSecurity()->generatePasswordHash($data['SignupForm']['password']);
            $user->create_time = CommonHelper::getCurrentTime();
            $user->mobile = $data['SignupForm']['mobile'];
            $result = $user->save();
            if ($result) {
                $loginresult = \Yii::$app->getUser()->login($user, 2);
                if ($loginresult) {
                    return $this->redirect(['index.php/web/home']);
                }
            } else {
                return null;
            }
        }
        return $this->render('register', ['model' => $model,]);
    }
    public function actionSms(){

        // 初始化REST SDK
//        $request = \Yii::$app->request;
//        $tel = $request->post('tel');


//主帐号
        $accountSid = '8aaf0708567749f00156789bb7f80282';

//主帐号Token
        $accountToken = '2b9a2a1a7d0a436fa6476a3a2035d812';

//应用Id
        $appId = '8aaf07085697eda30156a10a5dbb06d6';
        //$appId = '8a216da85697f5420156a1d606ed089e' 这是生产环境ps.susnion的ID

//请求地址，格式如下，不需要写https://
        $serverIP = 'app.cloopen.com';

//请求端口
        $serverPort = '8883';

//REST版本号
        $softVersion = '2013-12-26';

        $rest = new \REST($serverIP,$serverPort,$softVersion);

        $rest->setAccount($accountSid,$accountToken);
        $rest->setAppId($appId);

        $verifyC = new VerifyForm();
        $verifyC->verifyCode = \Yii::$app->request->post('code');
        if(!$verifyC->validate()){

            return '验证码不正确';
        }




        // 发送模板短信

        //接受前端传来的手机号;
        $tel = $_POST['tel'];


        //生成验证码,然后存到验证码表中,
        $verify = (string)rand(1000,9999);

        $request = \Yii::$app->request;

        $codeModel = new ValidateCode();

        $codeModel->create_time = CommonHelper::getCurrentTime();
        $codeModel->mobile = $tel;
        $codeModel->verify_code = $verify;
        $codeModel->save();

        $result = $rest->sendTemplateSMS($tel,[$verify,'1'],110309);//这个是 wap.hackerc.cn/web/home 的模板ID个APPID
        //$result = $rest->sendTemplateSMS($tel,[$verify,'1'],110416);//这个是生产环境的模板ID
        if ($result == NULL) {
            echo "result error!";
            return;
        }
        if ($result->statusCode != 0) {
            echo "error code :" . $result->statusCode . "<br>";
            echo "error msg :" . $result->statusMsg . "<br>";
            //TODO 添加错误处理逻辑

        } else {
            echo "Sendind TemplateSMS success!<br/>";
            // 获取返回信息
            $smsmessage = $result->TemplateSMS;
            echo "dateCreated:" . $smsmessage->dateCreated . "<br/>";
            echo "smsMessageSid:" . $smsmessage->smsMessageSid . "<br/>";

        }



    }

//Demo调用,参数填入正确后，放开注释可以调用
//sendTemplateSMS("手机号码","内容数据","模板Id");


    public function actionAgent()
    {
        return $this->render('agent');
    }

    //处理点击量ajax请求
    public function actionClickCount(){
        $request=\Yii::$app->request;
        $commodity_id=$request->get('commodity_id');
            $commodity=\Yii::$app->db->createCommand('UPDATE hcps_commodity SET click_count=click_count+1 WHERE  commodity_id=:id ')->bindParam(':id',$commodity_id)->execute();

        if($commodity){
            return json_encode(['code'=>0]);
        }
        else{
            return json_encode(['code'=>1]);
        }
    }



    //处理用户是否关注ajax请求
    public function actionIsFollow(){

        $openid=$_COOKIE['openid'];
        $access_token=$_COOKIE['access_token'];
        $url="https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
        echo file_get_contents($url);


    }

    //处理查看物流信息ajax请求
    public function actionViewLogistics(){
        $db = \Yii::$app->db;
        $request=\Yii::$app->request;
        $orderform_id=$request->post('orderform_id');
        $express_num= $db->createCommand('SELECT express_num FROM hcps_orderform WHERE orderform_id=:id')->bindValue(':id', $orderform_id)->queryScalar();
         echo json_encode($express_num);
    }




    //处理不在提示关注ajax请求
    public function actionNoRemind(){
//        $request=\Yii::$app->request;
        $user_id=\Yii::$app->user->id;
        $noRemind=\Yii::$app->db->createCommand('UPDATE hcps_user SET no_remind=1 WHERE  user_id=:id ')->bindParam(':id',$user_id)->execute();
        if($noRemind){
            return json_encode(['code'=>0]);
        }
        else{
            return json_encode(['code'=>1]);
        }

    }



}